package iot.servlet;

import iot.bean.Tdevice;
import iot.dao.DeviceDao;
import iot.utils.CodeExchange;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@SuppressWarnings("serial")
public class DeviceServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public DeviceServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	@SuppressWarnings({ "unchecked", "static-access" })
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 当进行用户登录、用户信息删除、用户信息添加和用户信息修改等操作时，数据递交给Servlet，并传递action参数，下文根据action参数执行对应操作
		String action = request.getParameter("action");
		if (action != null) {
			if (action.equals("delete")) {
				String id = request.getParameter("id");
				if (id != null && id.length() > 0) {
					DeviceDao deviceDao = new DeviceDao();
					if (deviceDao.delete(id)) {
						request.setAttribute("msg", "删除成功！");
					} else {
						request.setAttribute("msg", "删除失败！");
					}

				} else {
					response.sendRedirect("error.jsp");
					return;
				}
			} else if (action.equals("add")) {
				// 创建fileItemFactory工厂
				DiskFileItemFactory factory = new DiskFileItemFactory();
				// 创建实现文件上传的组件
				ServletFileUpload upload = new ServletFileUpload(factory);
				// 解决文件的中文乱码
				upload.setHeaderEncoding("ISO-8859-1");
				ArrayList<FileItem> items = null;
				Tdevice device = new Tdevice();
				try {
					// 应用parseRequest获取全部表单项，有文件域和普通表单域，都当成FileItem对象
					items = (ArrayList<FileItem>) upload.parseRequest(request);
				} catch (FileUploadException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

				Iterator<FileItem> it = items.iterator();
				while (it.hasNext()) {
					FileItem tempitem = it.next();// 取得表单中的一个元素，即表单项
					String itemName = tempitem.getFieldName();// 取得input标签的name属性值
					// isFormField()为true，则是普通表单域
					if (tempitem.isFormField()) {
						// 提到表单项文本内容，并进行中文乱码处理
						String content = CodeExchange.chinese(tempitem.getString());
						// 当前为isFormField()为true，则是普通表单域，把表单项内容放到JavaBean中存储。
						// Tdevice device=new Tdevice();
						device.setAddtime(new Timestamp((new Date()).getTime()));
						if (itemName.equals("dtid")) {
							device.setDtid(Long.parseLong(content));
						}
						if (itemName.equals("devicename")) {
							device.setDevicename(content);
						}
						if (itemName.equals("devicecode")) {
							device.setDevicecode(content);
						}

					}
					// 当前为isFormField()为false,判断表单域是文件域
					else {
						// type是file，上传的文件
						// 上传文件保存到服务器的路径
						if (tempitem.getName() != null & !"".equals(tempitem.getName())) {
							String newFileName = device.getDevicecode()+'.'+(CodeExchange.chinese(tempitem.getName()).split("\\.")[1]);
							File tempfile = new File(request.getSession().getServletContext().getRealPath("/")
									+ "photos\\"
									+ new File(newFileName));
							try {
								tempitem.write(tempfile);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							// 上传的文件存储到JavaBean中
							// tempfile.getCanonicalPath()，获取当前文件的绝对路径
							// lastIndexOf(String str):
							// 返回指定字符在此字符串中最后一次出现处的索引，如果此字符串中没有这样的字符，则返回 -1
							// substring(start,stop)，用于提取字符串中介于两个指定下标之间的字符。
							device.setDevicephoto("photos/"
									+ tempfile.getCanonicalPath().substring(
											tempfile.getCanonicalPath()
													.lastIndexOf("\\") + 1));
						} else 
							device.setDevicephoto("images/no-photo.gif");
					}
				}
				DeviceDao deviceDao = new DeviceDao();
				if (deviceDao.add(device)) {
					request.setAttribute("msg", "添加成功！");
				} else {
					request.setAttribute("msg", "添加失败！");
				}
			} else if (action.equals("update")) {
				String id = request.getParameter("id");
				if (id != null && id.length() > 0) {
					DeviceDao deviceDao = new DeviceDao();

					ArrayList<Tdevice> devices = deviceDao.query(" id=" + id);
					if (devices != null && devices.size() > 0) {
						Tdevice device = devices.get(0);
						request.setAttribute("device", device);

						request.getRequestDispatcher("deviceedit.jsp").forward(
								request, response);
						return;
					} else {
						response.sendRedirect("error.jsp");
						return;
					}

				} else {
					response.sendRedirect("error.jsp");
					return;
				}

			} else if (action.equals("updateSave")) {

				Tdevice device = new Tdevice();
				// 创建fileItemFactory工厂
				DiskFileItemFactory factory = new DiskFileItemFactory();
				// 创建实现文件上传的组件
				ServletFileUpload upload = new ServletFileUpload(factory);
				// 解决文件的中文乱码
				upload.setHeaderEncoding("ISO-8859-1");
				ArrayList<FileItem> items = null;

				try {
					// 应用parseRequest获取全部表单项，有文件域和普通表单域，都当成FileItem对象
					items = (ArrayList<FileItem>) upload.parseRequest(request);
				} catch (FileUploadException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

				Iterator<FileItem> it = items.iterator();
				while (it.hasNext()) {
					FileItem tempitem = it.next();// 取得表单中的一个元素，即表单项
					String itemName = tempitem.getFieldName();// 取得input标签的name属性值
					// isFormField()为true，则是普通表单域
					if (tempitem.isFormField()) {
						// 提到表单项文本内容，并进行中文乱码处理
						String content = CodeExchange.chinese(tempitem.getString());
						// 当前为isFormField()为true，则是普通表单域，把表单项内容放到JavaBean中存储。
						// Tdevice device=new Tdevice();
						device.setAddtime(new Timestamp((new Date()).getTime()));
						if (itemName.equals("dtid")) {
							device.setDtid(Long.parseLong(content));
						}
						if (itemName.equals("id")) {
							device.setId(Long.parseLong(content));
						}
						if (itemName.equals("devicename")) {
							device.setDevicename(content);
						}
						if (itemName.equals("devicecode")) {
							device.setDevicecode(content);
						}

					}
					// 当前为isFormField()为false,判断表单域是文件域
					else {
						// type是file，上传的文件
						// 上传文件保存到服务器的路径
						if (tempitem.getName() != null & !"".equals(tempitem.getName())) {
							String newFileName = device.getDevicecode()+'.'+(CodeExchange.chinese(tempitem.getName()).split("\\.")[1]);
							File tempfile = new File(request.getSession().getServletContext().getRealPath("/")
									+ "photos\\"
									+ new File(newFileName));
							//System.out.print(newFileName);
							try {
								tempitem.write(tempfile);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							// 上传的文件存储到JavaBean中
							// tempfile.getCanonicalPath()，获取当前文件的绝对路径
							// lastIndexOf(String str):
							// 返回指定字符在此字符串中最后一次出现处的索引，如果此字符串中没有这样的字符，则返回 -1
							// substring(start,stop)，用于提取字符串中介于两个指定下标之间的字符。
							device.setDevicephoto("photos/"
									+ tempfile.getCanonicalPath().substring(
											tempfile.getCanonicalPath()
													.lastIndexOf("\\") + 1));
						} else 
							device.setDevicephoto("images/no-photo.gif");
					}
				}
				DeviceDao deviceDao = new DeviceDao();
				if (deviceDao.update(device)) {
					request.setAttribute("msg", "修改成功！");
				} else {
					request.setAttribute("msg", "修改失败！");
				}

			} else {
				response.sendRedirect("error.jsp");
				return;
			}
		}

		// 查询条件
		String whereSQL = "";
		String keyword = CodeExchange.chinese(request.getParameter("keyword"));
		String fieldname = request.getParameter("fieldname");
		if (keyword != null && fieldname != null && fieldname.length() > 0
				&& keyword.length() > 0) {
			// id为整型
			if (fieldname.equals("id")) {
				whereSQL = fieldname + "=" + keyword;
				System.out.print(whereSQL);
			}
			// 其他为字符串型，要加入单引号
			else {
				whereSQL = fieldname + " like '%" + keyword + "%' ";
			}
			// 回传给页面显示查询条件，否则会清空
			request.setAttribute("fieldname", fieldname);
			request.setAttribute("keyword", keyword);

		}

		//
		String page = request.getParameter("page");
		if (page == null) {
			page = "1";
		}
		DeviceDao deviceDao = new DeviceDao();
		ArrayList<Tdevice> devices = new ArrayList<Tdevice>();
		devices = deviceDao.queryPage(whereSQL, Integer.parseInt(page));
		request.setAttribute("devices", devices);

		int total = deviceDao.count(whereSQL);
		request.setAttribute("total", total / deviceDao.PAGE_LENGTH + 1);

		request.setAttribute("currentPage", Integer.parseInt(page));
		request.getRequestDispatcher("devicelist.jsp").forward(request,
				response);

	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
